first_and_last.py
¶groups = {}
response = input('Word: ')
while response:
key = (response[0], response[-1])
if key not in groups:
groups[key] = []
groups[key].append(response)
response = input('Word: ')
print(groups)
Given the text of 1 Nephi, group words by preceding word.
Then use the result to randomly generate text.
nephi.py
¶def group_by_previous(words):
prev = None
groups = {}
for word in words:
word = word.strip('.,;!?')
if prev is None:
prev = word
continue
key = prev.lower()
if key not in groups:
groups[key] = []
groups[key].append(word)
prev = word
return groups
groups = group_by_previous("""
And it came to pass that I Nephi said unto my father
I will go and do the things which the Lord has commanded
for I know that the Lord giveth no commandments unto the
children of men save He shall prepare a way that they may
accomplish the things that He commandeth them
""".split())
groups
import random
word = 'and'
words = [word]
for _ in range(20):
word = random.choice(groups[word.lower()])
words.append(word)
print(" ".join(words))